import {getUserInfo, login} from "../api/user";
import {useStore} from "vuex";
import {UserInfo} from "../sql/domin";
import {UserMapper} from "../mappers/UserMapper";
import {computed} from "vue";


export function loginService(){

    const store = useStore()

    const getNetWorkType = () => {
        return new Promise<boolean>((resolve)=>{
            uni.getNetworkType({
                complete:result => {
                    let networkType = result.networkType || 'none'
                    if (networkType == 'none'){
                        resolve(false)
                    }else {
                        resolve(true)
                    }
                }
            })
        })
    }

    const checkToken = async ()=>{
        //(store.getters.token)
        if (store.getters.token == ''){
            //('登录')
            await onlineLogin(store.getters.userinfo.username,store.getters.userinfo.password)
        }
        if (store.getters.token != ''){
            //('验证')
            getUserInfo().then((res)=>{
                //(res)
                if (res.data.code != 200){
                    onlineLogin(store.getters.userinfo.username,store.getters.userinfo.password)
                }
            })
        }
    }

    // const netWorkType = computed(async ()=>{
    //     return await getNetWorkType()
    // })

    const onlineLogin = (username:string,password:string) =>{
        return new Promise((resolve, reject)=>{
            login(username,password).then(res=>{
                uni.hideLoading()
                if (res.data.code == 200){
                    store.dispatch("SET_TOKEN",res.data.token)
                    uni.setStorage({
                        key:'token',
                        data:res.data.token
                    })
                    store.dispatch('SET_ONLINE_STATUS',true)
                    uni.showToast({
                        title: '用户登录成功。',
                        icon: 'none',
                        duration: 2000
                    })
                    getUserInfo().then(infoRes=>{
                        resolve(infoRes.data)
                    })
                }else {
                    uni.showToast({
                        title: '用户登录失败。',
                        icon: 'none',
                        duration: 2000
                    })
                    reject(false)
                }
            })

        })
    }

    return {
        onlineLogin,
        // netWorkType
        getNetWorkType,
        checkToken
    }
}
